import os

from celery import Celery

# Set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'settings.base')

app = Celery('recruitment')

# Using a string here means the worker doesn't have to serialize
# the configuration object to child processes.
# - namespace='CELERY' means all celery-related configuration keys
#   should have a `CELERY_` prefix.
app.config_from_object('django.conf:settings', namespace='CELERY')

# Load task modules from all registered Django apps.
app.autodiscover_tasks()


@app.task(bind=True, ignore_result=True)
def debug_task(self):
    print(f'Request: {self.request!r}')


from celery.schedules import crontab

# add方式需要显示的import进来
from recruitment.tasks import add

# 定时任务方式二：在代码中配置定时任务
app.conf.beat_schedule = {
    'add-every-10-seconds': {
        'task': 'recruitment.tasks.add',
        'schedule': 10.0, # 10秒钟一次
        'args': (16, 4,), # 参数
    }
}


# 定时任务方式一：系统启动时添加定时任务
# 自动注册这些定时任务
@app.on_after_configure.connect
def setup_periodic_tasks(sender, **kwargs):
    sender.add_periodic_task(
        10.0,
        test.s('hello'),
        name='hello every 10',
    )
    sender.add_periodic_task(
        30.0,
        test.s('world'),
        expires=10
    )
    sender.add_periodic_task(
        crontab(hour=7, minute=30, day_of_week=1),
        test.s('Happy Mondays!'),
    )


# 定时任务方式三：系统运行的时候动态的添加
# import json
# from django_celery_beat.models import PeriodicTask, IntervalSchedule

# ## 先创建定时策略
# schedule, created = IntervalSchedule.objects.get_or_create(
#     every=10,  # 每10秒执行一次
#     period=IntervalSchedule.SECONDS,  # 每20秒执行一次
# )

# ## 再创建任务
# task = PeriodicTask.objects.create(
#     interval=schedule,
#     name='say_welcome3',
#     task='recruitment.celery.test',
#     args=json.dumps(['welcome']),
# )

@app.task
def test(arg):
    print(arg)
